package com.jfinal.weixin.demo.weather;

import com.alibaba.fastjson.JSON;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * http://apistore.baidu.com/apiworks/servicedetail/478.html
 * Created by wangxiaoyang on 16/8/27.
 */
public class HeWeatherApi {

    private static final String baseUrl = "http://apis.baidu.com/heweather/weather/free?city=";

    public static void main(String[] args) {
        HeWeatherBean heWeatherBean = getHeWeather(new OkHttpClient(), "北京");
    }

    public static HeWeatherBean getHeWeather(OkHttpClient httpClient, String cityInfo) {
        String url = baseUrl + cityInfo;
        Request request = new Request.Builder()
                .url(url)
                .addHeader("apikey", "1f1caef2b32c608aa9c63ac0965410da")
                .build();
        try {
            Response response = httpClient.newCall(request).execute();
            String result = response.body().string();
            int start = result.indexOf('[');
            int end = result.lastIndexOf(']');

            if (start > 0 && end > start) {
                result = result.substring(start + 1, end);
            }
            System.out.println("result1 \n" + result);
            HeWeatherBean heWeatherBean = JSON.parseObject(result, HeWeatherBean.class);
            System.out.println("heWeatherBean " + heWeatherBean.format());
            return heWeatherBean;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
